package com.zide.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zide.auth.constant.UserConstants;
import com.zide.auth.domain.entity.platform.PlatformConfig;
import com.zide.auth.mapper.platform.PlatformConfigMapper;
import com.zide.common.annotation.DataSource;
import com.zide.common.constant.CacheConstants;
import com.zide.common.core.domain.PageResult;
import com.zide.common.core.redis.ZiDeRedisUtil;
import com.zide.common.core.text.Convert;
import com.zide.common.enums.DataSourceType;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.StringUtils;
import com.zide.platform.service.PlatformConfigService;
import com.zide.platform.vo.result.config.PlatformConfigResultVO;
import com.zide.auth.vo.search.config.PlatformConfigSearchVO;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 参数配置 服务层实现
 *
 * @author zide
 */
@RequiredArgsConstructor
@Service
public class PlatformConfigServiceImpl implements PlatformConfigService {
    private final PlatformConfigMapper configMapper;
    private final ZiDeRedisUtil ziDeRedisUtil;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param id 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public PlatformConfig selectConfigById(Long id) {
        PlatformConfig config = new PlatformConfig();
        config.setId(id);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(ziDeRedisUtil.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        PlatformConfig config = new PlatformConfig();
        config.setConfigCode(configKey);
        PlatformConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            ziDeRedisUtil.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<PlatformConfig> selectConfigList(PlatformConfig config) {
        LambdaQueryWrapper<PlatformConfig> wrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotEmpty(config.getConfigCode())) {
            wrapper.like(PlatformConfig::getConfigCode, config.getConfigCode());
        }
        if(StrUtil.isNotEmpty(config.getConfigName())) {
            wrapper.like(PlatformConfig::getConfigName, config.getConfigName());
        }
        return configMapper.selectList(wrapper);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(PlatformConfig config) {
        int row = configMapper.insert(config);
        if (row > 0) {
            ziDeRedisUtil.setCacheObject(getCacheKey(config.getConfigCode()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(PlatformConfig config) {
        PlatformConfig temp = configMapper.selectById(config.getId());
        if (!StringUtils.equals(temp.getConfigCode(), config.getConfigCode())) {
            ziDeRedisUtil.deleteObject(getCacheKey(temp.getConfigCode()));
        }

        int row = configMapper.updateById(config);
        if (row > 0) {
            ziDeRedisUtil.setCacheObject(getCacheKey(config.getConfigCode()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param ids 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] ids) {
        for (Long id : ids) {
            PlatformConfig config = selectConfigById(id);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigCode()));
            }
            configMapper.deleteById(id);
            ziDeRedisUtil.deleteObject(getCacheKey(config.getConfigCode()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<PlatformConfig> configsList = configMapper.selectList();
        for (PlatformConfig config : configsList) {
            ziDeRedisUtil.setCacheObject(getCacheKey(config.getConfigCode()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = ziDeRedisUtil.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        ziDeRedisUtil.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(PlatformConfig config) {
        Long id = StringUtils.isNull(config.getId()) ? -1L : config.getId();
        LambdaQueryWrapper<PlatformConfig> wrapper = new LambdaQueryWrapper<PlatformConfig>().eq(PlatformConfig::getConfigCode, config.getConfigCode());
        PlatformConfig platformConfig = configMapper.selectOne(wrapper);
        if (StringUtils.isNotNull(platformConfig) && platformConfig.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public PageResult<PlatformConfigResultVO> searchPage(PlatformConfigSearchVO searchVO) {

        PageResult<PlatformConfig> sourceResult = configMapper.selectPage(searchVO);
        PageResult<PlatformConfigResultVO> result = new PageResult<>();
        BeanUtil.copyProperties(sourceResult,result);
        return result;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
